const express = require("express");
const app = express();
const path = require("path");

// 跨域
const cors = require("cors");

app.use(
  cors({
    // 允许任何域名访问
    origin: "*",
    // 允许任何请求头
    headers: "*",
    // 允许任何方法
    methods: "*",
    // 允许携带cookie
    credentials: true,
  })
);

// 处理 post 请求
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// 静态文件服务 - 用于提供上传的头像文件
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

const { expressjwt } = require("express-jwt");
app.use(
  
  expressjwt({
    secret: "liyu",
    algorithms: ["HS256"],
  }).unless({ path: ["/login", "/register", /^\/images\/.*$/, /^\/uploads\/.*$/] }) // 排除静态资源路径
);

// 引用 router
const listRouters = require("./server/route/list");
const loginRoutes = require("./server/route/login");
const registerRoutes = require("./server/route/reg");
const restaurantRoutes = require("./server/route/restaurant");
const cartRoutes = require("./server/route/cart");
const orderRoutes = require("./server/route/order");
const userRoutes = require("./server/route/user");
const admincaozuoRoutes = require("./server/route/alluser");
const rechargeRoutes = require("./server/route/recharge");
const marketingRoutes = require("./server/route/marketing");
const couponRoutes = require("./server/route/coupon");

app.use(listRouters);
app.use(loginRoutes);
app.use(registerRoutes);
app.use(restaurantRoutes);
app.use(cartRoutes);
app.use(orderRoutes);
app.use(userRoutes);
app.use(admincaozuoRoutes);
app.use(rechargeRoutes);
app.use('/marketing', marketingRoutes);
app.use(couponRoutes);

// 配置静态资源目录，包括图片
app.use(express.static("public"));
app.use("/uploads", express.static(path.join(__dirname, "uploads"))); // 指定上传文件的目录

// 添加一个路由中间件
app.use("/api/index", (req, res) => {
  // 直接返回 "hello api"
  res.send("hello api");
});

// 404 异常处理中间件，跳转到 web 目录下的 404.html
app.use((req, res) => {
  res.status(404).sendFile(__dirname + "/public/index.html");
});

// 登录过期处理中间件，发送 401 状态码
app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    res.status(401).send("登录过期，请重新登录");
  }
});

// 导入错误处理中间件
const errHandler = require("./server/utils/errcode");
app.use(errHandler);

app.listen(3000, () => {
  console.log("Server is running at http://127.0.0.1:3000");
});
